import {
  TAB_KEY,
  TAB_INDEX_KEY
} from '@/global-config'
// 初始化使用
const initTab = {
  id: '1',
  path: '/home',
  meta: {
    title: '首页',
    names: [], // 面包屑使用

  }
};


const tab = {
  state() {
    return {
      info: [initTab],
      tabIndex: '1'
    };
  },
  getters: {
    getTab: (state) => state.info,
    getTabIndex: (state) => state.tabIndex
  },
  mutations: {
    INIT_TAB: (state) => {
      state.tabIndex = '1';
      state.info = [initTab];
      // sessionStorage.setItem(TAB_KEY, JSON.stringify(state.info));
    },
    SET_TAB: (state, payload) => {
      // 查询当前tab是否存在 tab页签
      const findRes = state.info.find((i) => i.id == payload.id);
      // 新tab存储
      if (!findRes) {
        state.info.push(payload);
        sessionStorage.setItem(TAB_KEY, JSON.stringify(state.info));
      }
    },
    DEL_TAB: (state, payload) => {
      const index = state.info.findIndex((i) => i.id == payload);
      if (index != -1) {
        state.info.splice(index, 1);
        sessionStorage.setItem(TAB_KEY, JSON.stringify(state.info));
      }
    },
    SET_TAB_INDEX: (state, payload) => {
  
      state.tabIndex = typeof(payload) === 'string' ? payload: String(payload)

      sessionStorage.setItem(TAB_INDEX_KEY, JSON.stringify(state.tabIndex));
    }
  },

  // this.$stote.dispatch('tab/xxx')
  actions: {
    setTab({ commit }, payload) {
      commit('SET_TAB', payload);
    },
    delTab({commit}, payload){
      commit('DEL_TAB', payload)
    },
    setTabIndex({commit}, payload){
      commit('SET_TAB_INDEX', payload)
    },
    initTab({commit}){
      commit("INIT_TAB")
    }
  }
};
export default {
  namespaced: true,
  ...tab
};
